﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Administration;
using System.IO;
using System.Diagnostics;
using Microsoft.SharePoint;

namespace SPWebPartManager_ControlAdapter
{
    public class SPWebPartManager_ControlAdapterJobDefinition : SPJobDefinition
    {

        public const string JobName = "SPWebPartManager_ControlAdapterJob";


        public bool Installing
        {
            get
            {
                return (bool)this.Properties["Installing"];
            }
            set
            {
                this.Properties["Installing"] = value;
            }
        }

        public SPWebPartManager_ControlAdapterJobDefinition()
            : base()
        {
        }

        public SPWebPartManager_ControlAdapterJobDefinition(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, SPJobLockType.None)
        {
        }
        public SPWebPartManager_ControlAdapterJobDefinition(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.None)
        {
            this.Title = "SPWebPartManager_ControlAdapter Job";
        }

        public override void Execute(Guid targetInstanceId)
        {
            EventLog.WriteEntry(this.GetType().FullName, "Executed");
            SPWebApplication webApplication = this.WebApplication;
            if (Installing)
            {
                foreach (SPUrlZone zone in webApplication.IisSettings.Keys)
                {
                    // The settings of the IIS application to update
                    SPIisSettings settings = webApplication.IisSettings[zone];

                    string basePath = settings.Path.ToString();
                    string destPath = Path.Combine(basePath, "App_Browsers");
                    string fullfilename = Path.Combine(destPath, "SPWebPartManager_ControlAdapter.browser");
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        EventLog.WriteEntry(this.GetType().FullName, string.Format("Writing the file \"{0}\"", fullfilename));
                    }
                    );
                    System.IO.FileStream file = new System.IO.FileStream(fullfilename, FileMode.Create, FileAccess.Write);
                    System.IO.StreamWriter writer = new System.IO.StreamWriter(file);
                    System.IO.Stream resource = this.GetType().Assembly.GetManifestResourceStream("SPWebPartManager_ControlAdapter.FeatureCode.SPWebPartManager_ControlAdapter.browser");
                    System.IO.StreamReader reader = new System.IO.StreamReader(resource);
                    string s = reader.ReadToEnd();
                    s = s.Replace("{707D9AE2-D892-448f-8DC4-4BBC2C95770D}", typeof(SPWebPartManager_ControlAdapter).FullName + ", " + typeof(SPWebPartManager_ControlAdapter).Assembly.FullName);
                    writer.Write(s);
                    writer.Flush();
                    writer.Close();
                    reader.Close();

                    // Touch .browser-files to force activation of the control adapter
                    foreach (string filename in System.IO.Directory.GetFiles(destPath, "*.browser"))
                    {
                        System.IO.File.SetLastWriteTime(filename, DateTime.Now);
                    }
                }
            }
            else
            {
                foreach (SPUrlZone zone in webApplication.IisSettings.Keys)
                {
                    // The settings of the IIS application to update
                    SPIisSettings settings = webApplication.IisSettings[zone];

                    string basePath = settings.Path.ToString();
                    string destPath = Path.Combine(basePath, "App_Browsers");

                    string fullfilename = Path.Combine(destPath, "SPWebPartManager_ControlAdapter.browser");
                    if (System.IO.File.Exists(fullfilename))
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        EventLog.WriteEntry(this.GetType().FullName, string.Format("Removing the file \"{0}\"", fullfilename));
                    }
                    );
                        System.IO.File.Delete(fullfilename);
                    }

                    // Touch .browser-files to force de-activation of the control adapter
                    foreach (string filename in System.IO.Directory.GetFiles(destPath, "*.browser"))
                    {
                        System.IO.File.SetLastWriteTime(filename, DateTime.Now);
                    }
                }
            }
            base.Execute(targetInstanceId);
            this.Delete();
            this.Update();
        }

    }
}
